package com.tianqu.tms.www.car.controller;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.DateUtil;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn30100Bo;
import com.tianqu.tms.dto.TmsFragileStickerHistoryDto;
import com.tianqu.tms.dto.TroubleCarInfoDto;
import com.tianqu.tms.entity.*;
import com.tianqu.tms.www.car.viewhelper.CarCreationInputViewHelper;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author zhangxueliang 立体停车场入库结果controller
 */
public class CarCreationEasyInputResultCopntroller extends TmsController {
	private Logger logger = Logger.getLogger(CarCreationEasyInputResultCopntroller.class);
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();
		
		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarCreationInputViewHelper viewhelper = new CarCreationInputViewHelper();
			viewhelper = (CarCreationInputViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			viewhelper.setInsertFlag(1);
			
			TmsUserProfile profile = uc.getUserProfile();
			Sequence seq = Sequence.getInstance();
			Car car = Car.getInstance();
			car = car.findCarByVin(viewhelper.getVin());
			String serial = "";
			int updateInsertFlag = 0;
			String oldTempLicensePlate = car.getTempLicensePlate();
			if(car.getSerial()!=null&&!"".equals(car.getSerial())){
				serial = car.getSerial();
				updateInsertFlag = 2;
			}else {
				serial = seq.getSerial(1);
				updateInsertFlag = 1;
			}
			int registerStatus = viewhelper.getRegisterStatus();
			String lPlate = Registry.getConfig(TmsConstants.TMS_DEFLICENSEPLATE_KEY);//车牌前两位

			car.setSerial(serial);
			car.setStatus(1);
			car.setRegisterStatus(6);
			car.setCarName(viewhelper.getCarName());
			car.setMemberId(Integer.parseInt(viewhelper.getMemberId()));
			car.setVin(viewhelper.getVin());
			car.setIsMatch(viewhelper.getIsMatch());
			if(viewhelper.getFromType() == 2){
				car.setCatClass(1);
			}else if(viewhelper.getFromType() == 1){
				car.setCatClass(2);
			}else {
				if(!StringUtil.isNullOrBlank(viewhelper.getCarStyleId())){
					if(viewhelper.getCarStyleId().startsWith("S")){
						car.setCatClass(1);
					}else{
						car.setCatClass(2);
					}
				}else {
					car.setCatClass(2);
				}
			}
			if (!StringUtil.isNullOrBlank(viewhelper.getMileage())) car.setMileage(Integer.parseInt(StringUtil.removeDH(viewhelper.getMileage())));
			if (!StringUtil.isNullOrBlank(viewhelper.getPrice())) car.setPrice(Integer.parseInt(StringUtil.removeDH(viewhelper.getPrice())));
			if (!StringUtil.isNullOrBlank(viewhelper.getColor())) car.setColor(Integer.parseInt(viewhelper.getColor()));
			if (!StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())) car.setTempLicensePlate(viewhelper.getTempLicensePlate().toUpperCase());
			else car.setTempLicensePlate("");
			if(StringUtil.isNullOrBlank(viewhelper.getLicensePlate()) || lPlate.equals(viewhelper.getLicensePlate())) car.setLicensePlate("");
			else car.setLicensePlate(viewhelper.getLicensePlate().toUpperCase());
			car.setRegDate(viewhelper.getRegDate());
			car.setJqx(viewhelper.getJqx());
			car.setYearCarefulPeriod(viewhelper.getYearCarefulPeriod());
			car.setCompanyContactPerson(viewhelper.getCompanyContactPerson());
			car.setCompanyContactPhone(viewhelper.getCompanyContactPhone());
			car.setCarStyleId(viewhelper.getCarStyleId());
			car.setBrandId(viewhelper.getBrandId());
			car.setCarStyleId(viewhelper.getCarStyleId());
			car.setVendorId(viewhelper.getVendorId());
			car.setRemark(viewhelper.getRemark());
			car.setPhoto_1(viewhelper.getPhoto_1());
			car.setPhoto_2(viewhelper.getPhoto_2());
			car.setPhoto_3(viewhelper.getPhoto_3());
			car.setPhoto_4(viewhelper.getPhoto_4());
			car.setPhoto_5(viewhelper.getPhoto_5());
			car.setPhoto_6(viewhelper.getPhoto_6());
			car.setPhoto_7(viewhelper.getPhoto_7());
			car.setPhoto_8(viewhelper.getPhoto_8());
			car.setInsertUserId(profile.getUniqueId());
			car.setUpdateUserId(profile.getUniqueId());
			car.setIsShelve(viewhelper.getIsShelve());
			car.setTempLicensePlate(viewhelper.getTempLicensePlate().toUpperCase());
			//
			if (registerStatus == 3) {
				car.setRegisterStatus(6);
				car.setInsertTimeUpadateFlg(true);
				car.updateMarketCarInfo(car);
			} else {
				car.setEntryStatus(1);
				car.setAttestStatus(1);
				car.insertEasyCarInfo(car);
			}
			logger.info(this.getClass().getName() + " action market_car_info: serial:" + serial +" registerStatus:"+registerStatus);

			MarketCarService carService = MarketCarService.getInstance();
			if(updateInsertFlag == 1){//添加处理				
				carService.setSerial(serial);
				carService.setIsValid(3);
				carService.setCheckStatus(1);
				//插入 库存车辆业务表（tms_market_car_service）
				carService.insertCarServiceIsValid(carService);
				
				if(!StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())){//易碎贴
					//
					TmsFragileStickerHistory tmsFragileStickerHistory = TmsFragileStickerHistory.getInstance();
					TmsFragileStickerHistoryDto dto = new TmsFragileStickerHistoryDto();
					dto.setIsPay(viewhelper.getIsPay());
					dto.setMemberId(viewhelper.getMemberId());
					dto.setPutType("1");//第一次发帖
					dto.setSerial(serial);
					dto.setFragileStickerId(viewhelper.getTempLicensePlate().toUpperCase());
					dto.setInsertUserId(profile.getUniqueId());

					tmsFragileStickerHistory.insert(dto);
				}
				
			}else if(updateInsertFlag == 2){//修改处理
				carService = carService.findCarServiceInfoBySerial(serial);
				if(StringUtil.isNullOrBlank(carService.getSerial())){
					carService.setSerial(serial);
					carService.setIsValid(3);
					carService.setCheckStatus(1);
					//插入 库存车辆业务表（tms_market_car_service）
					carService.insertCarServiceIsValid(carService);
				}else {
					carService.setSerial(serial);
					carService.setIsValid(3);
					carService.setCheckStatus(1);
					carService.setCheckPrice(0);
					carService.setTransferPrice(0);
					carService.setCheckImgPath("");
					carService.setCheckTime(null);
					carService.setCheckValidTime(null);
					carService.setCheckUser("");
					carService.setIsRebate(0);//无须返利
					//更新 库存车辆业务表（tms_market_car_service）
					carService.updateCarServiceAllInfo(carService);
				}
				
				if(!StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())
						&& !oldTempLicensePlate.equals(viewhelper.getTempLicensePlate())){//易碎贴
					//
					TmsFragileStickerHistory tmsFragileStickerHistory = TmsFragileStickerHistory.getInstance();
					TmsFragileStickerHistoryDto dto = new TmsFragileStickerHistoryDto();
					dto.setIsPay(viewhelper.getIsPay());
					dto.setMemberId(viewhelper.getMemberId());
					dto.setPutType("1");//第一次发帖
					dto.setSerial(serial);
					dto.setFragileStickerId(viewhelper.getTempLicensePlate().toUpperCase());
					dto.setInsertUserId(profile.getUniqueId());

					tmsFragileStickerHistory.insert(dto);
				}
			}
			String vinTemp = viewhelper.getVin();
			if(vinTemp.length() > 8) vinTemp = vinTemp.substring(vinTemp.length()-8,vinTemp.length());
			
			MarketCarInfoTemp carInfoTemp = MarketCarInfoTemp.getInstance();
			carInfoTemp = carInfoTemp.findCarTempInfoByVin(vinTemp);
			if(!StringUtil.isNullOrBlank(carInfoTemp.getVin())){
				boolean isModifyAttestStatus = false;
				if(carInfoTemp.getTag1Skip() == 2 || carInfoTemp.getTag2Skip() == 2 || StringUtil.isNotBlank(carInfoTemp.getTempLicensePlate())){
					isModifyAttestStatus = car.getAttestStatus() != carInfoTemp.getAttestStatus();
					car.setSerial(serial);
					car.setMileage(carInfoTemp.getMileage());
					car.setPhoto_1(carInfoTemp.getPhoto1());
					car.setPhoto_2(carInfoTemp.getPhoto2());
					car.setPhoto_3(carInfoTemp.getPhoto3());
					car.setPhoto_4(carInfoTemp.getPhoto4());
					car.setPhoto_5(carInfoTemp.getPhoto5());
					car.setPhoto_6(carInfoTemp.getPhoto6());
					car.setPhoto_7(carInfoTemp.getPhoto7());
					car.setPhoto_8(carInfoTemp.getPhoto8());
					car.setAttestStatus(carInfoTemp.getAttestStatus());
					car.setEntryStatus(4);
					if(StringUtil.isNotBlank(carInfoTemp.getTempLicensePlate())) car.setTempLicensePlate(carInfoTemp.getTempLicensePlate().toUpperCase());
					car.setColor(carInfoTemp.getColor());
					//更新 库存车辆信息表（tms_market_car_info）
					car.updateMarketCarIsMatchInfo(car,carInfoTemp.getTag1Skip(),carInfoTemp.getTag2Skip());
				}
				//2）如果库存车辆信息采集表（tms_market_car_info_temp）的车辆检测是否跳过（tag2Skip）为“2：正常”
				if(carInfoTemp.getTag2Skip() == 2){
					//如果车辆检测状态（attestStatus）的值被修改，并且库存车辆信息采集表（tms_market_car_info_temp）的车辆检测状态（attestStatus）为非“1：未检测、2：放心车“
					if(isModifyAttestStatus && carInfoTemp.getAttestStatus() !=1 && carInfoTemp.getAttestStatus()!=2){
						TroubleCarInfoDto troubleInfo = car.getTroubleCarInfobyVin(car.getVin());
						if(troubleInfo == null){
							TroubleCarInfoDto dto = new TroubleCarInfoDto();
							dto.setTroubleType(car.getAttestStatus());
							dto.setVin(car.getVin());
							car.insertTroubleCarInfo(dto);
						}else{
							TroubleCarInfoDto dto = new TroubleCarInfoDto();
							dto.setTroubleType(car.getAttestStatus());
							dto.setVin(car.getVin());
							car.updateTroubleCarInfo(dto);
						}
					}else if(isModifyAttestStatus && carInfoTemp.getAttestStatus() ==2){//如果车辆检测状态（attestStatus）的值被修改，并且库存车辆信息采集表（tms_market_car_info_temp）的车辆检测状态（attestStatus）为“2：放心车
						TroubleCarInfoDto troubleInfo = car.getTroubleCarInfobyVin(car.getVin());
						if(troubleInfo!=null){
							TroubleCarInfoDto dto = new TroubleCarInfoDto();
							dto.setTroubleType(car.getAttestStatus());
							dto.setVin(car.getVin());
							car.deleteTroubleCarInfo(dto);
						}
					}
					
					if(carInfoTemp!=null && StringUtil.isNotBlank(carInfoTemp.getTempLicensePlate())){
						TmsFragileStickerHistory tmsFragileStickerHistory = TmsFragileStickerHistory.getInstance();
						TmsFragileStickerHistoryDto dto = new TmsFragileStickerHistoryDto();
						dto.setFragileStickerId(carInfoTemp.getTempLicensePlate().toUpperCase());
						dto.setMemberId(car.getMemberId()+"");
						if(StringUtil.isNullOrBlank(viewhelper.getTempLicensePlate())) dto.setPutType("1");
						else dto.setPutType("2");
						dto.setIsPay("2");
						dto.setSerial(viewhelper.getSerial());
						dto.setInsertUserId(profile.getUniqueId());
						tmsFragileStickerHistory.insert(dto);
					}
				}
				//
				carInfoTemp.setId(carInfoTemp.getId());
				carInfoTemp.setSerial(car.getSerial());
				carInfoTemp.setIsMatch(2);
				//更新 库存车辆信息采集表（tmsapp_market_car_info_temp）
				carInfoTemp.updateCarMatchInfo(carInfoTemp);;
				
				if(carInfoTemp.getTag3Skip() == 2){
					carService.setSerial(serial);				
					carService.setCheckStatus(carInfoTemp.getCheckStatus());				
					if(carInfoTemp.getCheckStatus() == 2){
						carService.setIsValid(2);//有效
						carService.setCheckImgPath(carInfoTemp.getCheckImgPath());
						carService.setCheckUser(carInfoTemp.getInsertUser());
						carService.setCheckTime(carInfoTemp.getInsertTime());				
						carService.setCheckValidTime(getAfterMonthTime());
					}else {
						carService.setIsValid(3);//无效
						carService.setCheckImgPath("");
						carService.setCheckUser("");
						carService.setCheckTime(null);
						carService.setCheckValidTime(null);
					}
					//更新库存车辆业务表（tms_market_car_service）
					carService.updateCarServiceInfo(carService);
				}
			}
			Member member = Member.getInstance();
			member = member.findCarScoreByMemberId(viewhelper.getMemberId());
			String isAutoPayForRegister = Registry.getConfigFromDb(TmsConstants.ISAUTOPAYFORREGISTER);	
			int checkPrice = Integer.valueOf(Registry.getConfigFromDb(TmsConstants.CHECKPRICE));
			int transferPrice = Integer.valueOf(Registry.getConfigFromDb(TmsConstants.TRANSFERPRICE));
			int virtualMargin = Integer.valueOf(member.getVirtualMargin());
			int isPay = 2;
			int paymentAmount = 0;
			String apiRemarks = "";
			String carHandleInfoRemarks = "";
			if(("3".equals(isAutoPayForRegister)) || (("2".equals(isAutoPayForRegister))&&(virtualMargin >= (checkPrice + transferPrice)))){
				carService.setSerial(serial);
				carService.setCheckPrice(1);//“1：缴费但未使用”
				carService.setTransferPrice(checkPrice+transferPrice);
				//更新  库存车辆业务表（tms_market_car_service）
				carService.updateCarServicePrice(carService);
				
				String memberId = viewhelper.getMemberId();
				int virtualprice = virtualMargin - checkPrice - transferPrice;
				//更新 会员基本信息数据表（tms_member）
				member.updateMemberVirtualMargin(memberId,virtualprice);
				
				String remark = "库存登记预缴交易过户费";
				int price = checkPrice + transferPrice;
				
				IntegralRegister register = new IntegralRegister();
				register.setMemberId(memberId);//会员编号
				register.setMemberType(1);//会员类型
				register.setChargeType(12);//业务处理类型
				register.setTransferPrice(price);//处理金额
				register.setPlusMinus(2);//业务处理方式
				register.setRemark(remark);//备注
				register.setInsertUserId(profile.getUniqueId());//插入用户
				register.setSerial("");//车辆流水号
				register.setLicensePlate("");//车牌号码
				register.setIntegral(0);//处理积分数
				//插入 财务流水记录表（tms_integral_register）
				register.insertRegisterInfo(register);
				isPay = 1;
				paymentAmount = price;
				apiRemarks = remark;
				carHandleInfoRemarks = "库存登记预缴费用{"+price+"}元";
			}
			
			//插入 库存车辆特殊处理记录表（tms_market_car_handleInfo）
			MarketCarHandleInfo carHandleInfo = new MarketCarHandleInfo();
			carHandleInfo.setSerial(serial);			
			carHandleInfo.setIsPush(2);
			carHandleInfo.setPhoto(viewhelper.getAcceptorImage());
			carHandleInfo.setUpdateUserId(profile.getUniqueId());
			if(updateInsertFlag == 1) carHandleInfo.setHandleType(13);	//添加处理			
			else carHandleInfo.setHandleType(14);//修改处理		
			if(isPay == 1){
				carHandleInfo.setPushContent(carHandleInfoRemarks);
			}else {
				carHandleInfo.setPushContent("");
			}
			carHandleInfo.setRemark(viewhelper.getHandleInfoRemark());
			
			carHandleInfo.insertCarHandleInfo(carHandleInfo);
			
			// 1、【TMS】新增入库（库存不存在情况的插入保存）=》【车代办】同步
			car = car.findCarBySerial(serial);
			String licensePlate = car.getLicensePlate().toUpperCase();
			String vin = car.getVin();
			int mileage = car.getMileage();
			int price = car.getPrice();
			int color = car.getColor();
			String regDate = car.getRegDate();
			String jqx = car.getJqx();
			String contactPerson = car.getCompanyContactPerson();
			String contactPhone = car.getCompanyContactPhone();
			String brandId = car.getBrandId();
			String yearCarefulPeriod = car.getYearCarefulPeriod();
			String attrIntro = car.getRemark();
			String carStyleId = car.getCarStyleId();
			String photo1 = car.getPhoto_1();
			String photo2 = car.getPhoto_2();
			String photo3 = car.getPhoto_3();
			String photo4 = car.getPhoto_4();
			String photo5 = car.getPhoto_5();
			String photo6 = car.getPhoto_6();
			String photo7 = car.getPhoto_7();
			String photo8 = car.getPhoto_8();
			String vendorId = car.getVendorId();
			String memberId = String.valueOf(car.getMemberId());
			int isMatch = car.getIsMatch();
			String carNmae = car.getCarName();
			int catClass = car.getCatClass();
			int registerStatusNo = car.getRegisterStatus();
			int attestStatus = car.getAttestStatus();
		 
			MobileMessage message = new MobileMessage();
			message.putValue("Serial", serial);
			message.setMessage("【TMS】新增入库（库存不存在情况的插入保存）=》【车代办】同步,Serial为#Serial#");
			TransferDataSyn30100Bo api = new TransferDataSyn30100Bo();
			api.setMobileMessage(message);
			api.setSerial(serial);
			api.setLicensePlate(licensePlate);
			api.setVin(vin);
			api.setMileage(mileage);
			api.setBrandId(brandId);
			api.setCarStyleId(carStyleId);
			api.setVendorId(vendorId);
			api.setColor(color);
			api.setMemberId(memberId);
			api.setPrice(price);
			api.setRegDate(regDate);
			api.setJqx(jqx);
			api.setYearCarefulPeriod(yearCarefulPeriod);
			api.setContactPerson(contactPerson);
			api.setContactPhone(contactPhone);
			api.setRemark(attrIntro);
			api.setPhoto1(photo1);
			api.setPhoto2(photo2);
			api.setPhoto3(photo3);
			api.setPhoto4(photo4);
			api.setPhoto5(photo5);
			api.setPhoto6(photo6);
			api.setPhoto7(photo7);
			api.setPhoto8(photo8);
			api.setIsMatch(isMatch);
			api.setRegisterStatus(registerStatusNo);
			api.setCarName(carNmae);
			api.setCatClass(catClass);
			api.setIsShelve(car.getIsShelve());
			api.setMarketNo(TmsConstants.MARKET_NO);
			api.setAttestStatus(attestStatus);
			api.setIsPay(isPay);
			api.setPaymentAmount(paymentAmount);
			api.setRemarks(apiRemarks);
			api.setPushFlag(1);
			api.setTempLicensePlate(car.getTempLicensePlate().toUpperCase());
			PullingExecutor.getInstance().submit(api);
			
			viewhelper.setSerial(serial);
			uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			
			logger.info(this.getClass().getName() + "#pulling parameter:" + api.toString());
			
			//
			controller.commit();
			
			
		} catch (Exception e) {
			try {
				logger.error(this.getClass().getName() + ", errorMessage:"+e.getMessage());
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}
		logger.debug(this.getClass().getName() + "#execute was completed.");
	}

	private Timestamp getAfterMonthTime() {
		Calendar c = Calendar.getInstance();// 获得一个日历的实例
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = sdf.parse(DateUtil.getCurrentTime());// 初始日期
		} catch (Exception e) {

		}
		c.setTime(date);// 设置日历时间
		c.add(Calendar.MONTH, 1);// 加1个月
		Timestamp dateTime = new Timestamp(c.getTime().getTime());
		return dateTime;
	}
}
